package com.lzc;


import com.lzc.listener.ListenerOnStartEvent;
import com.lzc.listener.StartEvent;
import javafx.application.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.Resource;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Locale;
import java.util.Map;

@SpringBootApplication
public class ApplicationRun {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException {

        ConfigurableApplicationContext context = SpringApplication.run(ApplicationRun.class, args);

        Field field = DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects");
        field.setAccessible(true);
        Map<String, Object> map = (Map<String, Object>) field.get(context.getBeanFactory());

        // 获取单例map集合 遍历
        map.entrySet().stream().filter( a -> a.getKey().startsWith("listener"))
                .forEach( a -> {
                    System.out.println(a.getKey()+"="+a.getValue());
                });

        //---------------------------ApplicationContext-------------------------------------------------

        // applicationContext 的扩展功能1 MessageSource接口 ： 国际化
        System.out.println(context.getMessage("hi", null, Locale.CHINA));

        // applicationContext 的扩展功能2 ResourcePatternResolver接口 ： 根据通配符获取文件资源
        Resource[] resources = context.getResources("classpath*:META-INF/spring.factories");
        for(Resource resource : resources){
            System.out.println(resource);
        }

        // applicationContext 的扩展功能3 EnvironmentCapable接口 ： 获取环境变量资源信息
        ConfigurableEnvironment environment = context.getEnvironment();
        System.out.println(environment.getProperty("server.port"));

        // applicationContext 的扩展功能4 ApplicationEventPublisher接口 ： 发布事件
        context.publishEvent(new StartEvent("事件"));
    }

}